package com.hexu.event.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.hexu.event.entity.User;
import com.hexu.event.util.JdbcUtil;

public class RegisterDao {

    //增加用户
    public boolean addUser(User user){
        String sql_1 = "insert into user(phone_number,password,username,system_balance,sex)"
                + " values (?,?,?,?,?);";
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JdbcUtil.getConn();
            ps = conn.prepareStatement(sql_1);
            //Base64 加密
            //View层set的数据
            ps.setString(1, user.getPhoneNumber());
            ps.setString(2, JdbcUtil.encrypt(user.getPassword()));
            ps.setString(3,user.getUserName());
            ps.setInt(4, user.getSystemBalance());
            ps.setString(5, user.getSex());
            ps.executeUpdate();

            //添加成功
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            JdbcUtil.close(conn, ps, null);
        }
        //添加失败
        return false;
    }

    //检索是否存在一样的手机号
    public boolean existPhoneNumber(String phoneNumber){
        String sql = "SELECT phone_number FROM USER UNION ALL SELECT phone_number FROM administrator";
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtil.getConn();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                if(phoneNumber.equals(rs.getString("phone_number").toString())) {
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            JdbcUtil.close(conn, ps, rs);
        }

        return true;
    }

}
